<template>
  <div class="commodity-list-container">
    <div class="search-bar">
      <t-input
        v-model="keyword"
        placeholder="请输入商品名称或标签搜索"
        style="width: 300px"
      />
      <t-button
        theme="primary"
        @click="handleSearch"
        style="margin-left: 10px"
      >
        搜索
      </t-button>
      <t-button
        theme="default"
        variant="outline"
        @click="resetSearch"
        style="margin-left: 10px"
      >
        重置
      </t-button>
      <t-button
        theme="primary"
        @click="handleAdd"
        style="margin-left: auto"
      >
        <t-icon name="add" /> 新增商品
      </t-button>
    </div>

    <t-table
      :data="tableData"
      :columns="columns"
      :loading="loading"
      row-key="id"
    >
      <template #operation="{ row }">
        <t-button
          variant="text"
          size="small"
          @click="handleView(row.id)"
        >
          查看
        </t-button>
        <t-button
          variant="text"
          size="small"
          @click="handleEdit(row)"
        >
          编辑
        </t-button>
        <t-button
          variant="text"
          size="small"
          theme="danger"
          @click="handleDelete(row.id)"
        >
          删除
        </t-button>
      </template>
    </t-table>

    <div class="pagination">
      <t-pagination
        :current="pageNum"
        :page-size="pageSize"
        :total="total"
        @change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑商品弹窗 -->
    <commodity-form
      v-if="showForm"
      :visible="showForm"
      :edit-data="editData"
      @close="showForm = false"
      @success="handleFormSuccess"
    />

    <!-- 商品详情弹窗 -->
    <commodity-detail
      v-if="showDetail"
      :visible="showDetail"
      :commodity-id="detailId"
      @close="showDetail = false"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, h } from 'vue';
import {
  Table as TTable,
  Button as TButton,
  Input as TInput,
  Pagination as TPagination,
  Icon as TIcon,
  Tag,
  Message
} from 'tdesign-vue-next';
import CommodityForm from './CommodityForm.vue';
import CommodityDetail from './CommodityDetail.vue';
import commodityApi from '../../api/commodity';

// 表格数据
const tableData = ref()
const columns = ref([
  { title: 'ID', colKey: 'id', width: 80 },
  { title: '标题', colKey: 'title', width: 80 },
  {
    title: '商品图片',
    field: 'image',
    width: 100,
    cell: (_, { row }) => {
      const isImageValid = row?.image && row.image.trim() !== '';
      if (isImageValid) {
        return h('img', {
          src: row.image,
          style: { width: '50px', height: '50px', objectFit: 'cover', border: '1px solid #eee' },
          onerror: (e) => { e.target.src = '/images/default-placeholder.png'; },
        });
      }
      return h('div', {
        style: { width: '50px', height: '50px', lineHeight: '50px', textAlign: 'center', border: '1px dashed #ccc', fontSize: '12px', color: '#999' },
      }, '无图片');
    },
  },
  { title: '售价', colKey: 'price', width: 100 },
  { title: '原价', colKey: 'originalPrice', width: 100 },
  { title: '排序', colKey: 'sortOrder', width: 80 },
   {
    title: '状态',
    colKey: 'status', // 注意：TDesign 表格列通常用 colKey 对应数据字段，与 field 功能一致
    width: 80,
    cell: (_, { row }) => {
      const status = row?.status;
       let label, theme;
       if (status === 1) {
        label = '正常';
        theme = 'success'; // 绿色
      } else if (status === 0) {
        label = '禁用';
        theme = 'danger'; // 红色
      } else {
        label = '未知';
        theme = 'warning'; // 黄色
      }
      return h(Tag, {
        theme: theme, // 主题色
        shape: 'round', // 可选：圆角样式更美观
        variant: 'light-outline' // 可选：浅色边框风格
      }, label); // 标签文本内容
    },
  },
  { title: '标签', colKey: 'tagsText', width: 200 },
  { title: '操作', colKey: 'operation', width: 200 }
]);

// 分页和搜索参数
const keyword = ref('');
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);

// 弹窗控制
const showForm = ref(false);
const showDetail = ref(false);
const editData = ref(null);
const detailId = ref(null);

// 页面加载时获取数据
onMounted(() => {
  fetchCommodityList();
});

// 获取商品列表
const fetchCommodityList = async () => {
  try {
    loading.value = true;
    const res = await commodityApi.getCommodityPage(
      keyword.value,
      pageNum.value,
      pageSize.value
    );
    console.log(res)
    tableData.value = res.data.records;
    total.value = 1;
  } catch (err) {
    message.error('获取商品列表失败');
    console.error(err);
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  pageNum.value = 1;
  fetchCommodityList();
};

// 重置搜索
const resetSearch = () => {
  keyword.value = '';
  pageNum.value = 1;
  fetchCommodityList();
};

// 分页变化
const handlePageChange = (page) => {
  pageNum.value = page;
  fetchCommodityList();
};

// 新增商品
const handleAdd = () => {
  editData.value = null;
  showForm.value = true;
};

// 编辑商品
const handleEdit = (row) => {
  editData.value = { ...row };
  showForm.value = true;
};

// 查看详情
const handleView = (id) => {
  detailId.value = id;
  showDetail.value = true;
};

// 删除商品
const handleDelete = async (id) => {
  if (confirm('确定要删除该商品吗？')) {
    try {
      await commodityApi.deleteCommodity(id);
      message.success('删除成功');
      fetchCommodityList();
    } catch (err) {
      message.error('删除失败');
      console.error(err);
    }
  }
};

// 表单提交成功回调
const handleFormSuccess = () => {
  showForm.value = false;
  fetchCommodityList();
};
</script>

<style scoped>
.commodity-list-container {
  padding: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
